package com.woniu.login.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.woniu.common.dto.LoginDto;
import com.woniu.common.entity.Result;
import com.woniu.common.entity.Verifycode;
import com.woniu.login.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

//获取验证码controller
@RestController
public class VerifyCodeController {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    LoginService loginService;

    @GetMapping("/verifyCode/create")
    public Result create(){
        //生成随机4位验证码
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100, 4, 6);
        String code = lineCaptcha.getImageBase64Data();

        //生成一个uuid
        String uuid = UUID.randomUUID().toString().replace("-", "");

        //将验证码存入redis，并且设置2分钟过期时长
        redisTemplate.opsForValue().set("code:"+uuid, lineCaptcha.getCode(), 2, TimeUnit.MINUTES);

        //  将uuid和验证码返回给前端
        return Result.ok(new Verifycode(uuid, code));
    }

    //  处理认证失败异常
    @GetMapping("/expiredJwtException")
    public void expiredJwtException(HttpServletRequest request){
        IllegalStateException exception = (IllegalStateException) request.getAttribute("expiredJwtException");
        throw exception;
    }
    //  发送邮箱验证码
    @PostMapping("/mailcode")
    public Result mailcode(@RequestBody LoginDto loginDto){
        //  生成6位验证码
        int emailcode = 100000 + new Random().nextInt(900000);
        System.out.println("邮箱验证码为："+emailcode);
        System.out.println("用户名为："+loginDto.getAaname());
        // 发送邮箱验证码
        loginService.sendEmail(loginDto.getAaname(),emailcode);
        //  将验证码存入redis，并且设置2分钟过期时长
        redisTemplate.opsForValue().set("emailcode:"+loginDto.getAaname(), emailcode, 2, TimeUnit.MINUTES);
        return Result.ok();
    }
}
